package com.konsung.ksdc.manager.shop;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.konsung.ksdc.R;
import com.konsung.ksdc.bean.CommentInfoBean;
import com.konsung.ksdc.bean.ProductInfoBean;
import com.konsung.ksdc.bean.netbean.CartDetailNetBean;
import com.konsung.ksdc.bean.netbean.ProductDetailNetBean;
import com.konsung.ksdc.bean.netbean.RegisterUserNetBean;
import com.konsung.ksdc.common.database.DatabaseHelper;
import com.konsung.ksdc.common.network.RequestCallback;
import com.konsung.ksdc.common.network.RequestUtils;
import com.konsung.ksdc.common.network.ResponseBean;
import com.konsung.ksdc.common.utils.Constants;
import com.konsung.ksdc.common.utils.DensityUtils;
import com.konsung.ksdc.common.utils.PreferenceUtils;
import com.konsung.ksdc.common.utils.StringUtils;
import com.konsung.ksdc.common.utils.ToastUtils;
import com.konsung.ksdc.common.widget.NumEditText;
import com.konsung.ksdc.common.widget.OnMultiClickListener;
import com.konsung.ksdc.common.widget.ProductTypeBottomPop;
import com.konsung.ksdc.config.NetConfig;
import com.konsung.ksdc.manager.appmain.BaseActivity;
import com.konsung.ksdc.manager.comment.ProductAllCommentActivity;
import com.konsung.ksdc.manager.community.ChatActivity;
import com.squareup.picasso.Picasso;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * 商品详情页面
 * Created by Administrator on 2016/5/17 0017.
 */
public class ProductDetailActivity extends BaseActivity implements View
        .OnClickListener, ViewPager.OnPageChangeListener {
    private static final int MSG_UPDATE_DETAIL = 10010;
    public static final String SHOPPING_NUM = "shoppingNum";
    public static final String PRODUCT_NET_BEAN = "productNetBean";
    public static final String TYPE_BUY = "type_buy";
    public static final String PRODUCT_ICON_URL = "productIconUrl";
    public static final int TYPE_BUY_DIRECT = 10100;
    public static final String PRODUCT_INFO_DATA = "product_info_data";
    public static final String COMMENT_DATA = "comment_data";
    private List<CartDetailNetBean> cartDetailNetBeans; // 购物车数量
    @Bind(R.id.vp_product_detail)
    ViewPager vpProductDetail;
    @Bind(R.id.lv_container)
    LinearLayout mPointContainer; // 轮播容器
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.tv_subtitle)
    TextView tvSubtitle;
    @Bind(R.id.tv_real_price)
    TextView tvRealPrice;
    @Bind(R.id.tv_discount_price)
    TextView tvDiscountPrice;
    @Bind(R.id.tv_product_selled_num)
    TextView tvProductSelledNum;
    @Bind(R.id.ll_type_container)
    LinearLayout llTypeContainer;
    @Bind(R.id.tv_comment_num_container)
    TextView tvCommentNumContainer;
    @Bind(R.id.tv_user_name)
    TextView tvUserName;
    @Bind(R.id.tv_comment)
    TextView tvComment;
    @Bind(R.id.tv_comment_time)
    TextView tvCommentTime;
    @Bind(R.id.tv_product_type)
    TextView tvProductType;
    @Bind(R.id.btn_all_comments)
    Button btnAllComments;
    @Bind(R.id.linear_comment)
    LinearLayout llContainer;
    @Bind(R.id.comment_no)
    TextView tvCommentNone;
    @Bind(R.id.rl_back)
    RelativeLayout rlBack;
    @Bind(R.id.tab_tv_title)
    TextView tabTvTitle;
    @Bind(R.id.tv_save)
    TextView tvSave;
    @Bind(R.id.iv_counsel)
    ImageView ivCounsel;
    @Bind(R.id.rl_title_container)
    RelativeLayout rlTitleContainer;
    @Bind(R.id.view_bg)
    View viewBg;
    @Bind(R.id.ll_add2cart)
    LinearLayout llAdd2cart;
    @Bind(R.id.iv_product_param_pic)
    ImageView ivProductParamPic;
    @Bind(R.id.btn_buy_now)
    Button btnBuyNow;
    @Bind(R.id.net_count)
    NumEditText netCount;
    @Bind(R.id.tv_remain_num)
    TextView tvRemainNum;
    @Bind(R.id.rl_product_detail_container)
    RelativeLayout rlProductDetailContainer;
    @Bind(R.id.iv_user_head)
    ImageView ivUserHead;

    List<View> viewList = new ArrayList<>();
    private ProductDetailNetBean productDetailNetBean;
    private ProductInfoBean productInfoBean;
    private String repertory; // 库存

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_UPDATE_DETAIL:
                    ArrayList<CommentInfoBean> evaluates = (ArrayList<CommentInfoBean>)
                            productDetailNetBean.getEvaluates();
                    if (evaluates != null) {
                        llContainer.setVisibility(View.VISIBLE);
                        tvCommentNone.setVisibility(View.GONE);
                    } else {
                        llContainer.setVisibility(View.GONE);
                        tvCommentNone.setVisibility(View.VISIBLE);
                    }
                    loadPic(productDetailNetBean.getUrls(),
                            productDetailNetBean.getParamUrl());
                    loadStringData(productDetailNetBean);
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 加载字符串文字显示
     * @param productDetailNetBean 商品详情Bean
     */
    private void loadStringData(ProductDetailNetBean productDetailNetBean) {
        tvTitle.setText(productDetailNetBean.getProductName());
        tvSubtitle.setText(productDetailNetBean.getSubTitle());
        tvDiscountPrice.setText(StringUtils.appendPay(productDetailNetBean
                .getMarketPrice()));
        tvRealPrice.setText(StringUtils.appendPay(productDetailNetBean
                .getMemberPrice()));
        tvProductSelledNum.setText(productDetailNetBean.getShoppingers());
        List<CommentInfoBean> commentInfoBeanList = productDetailNetBean
                .getEvaluates();
        if (commentInfoBeanList != null && commentInfoBeanList.size() > 0) {
            Picasso.with(this)
                    .load(StringUtils.appendPicPath(commentInfoBeanList.get(0).getUserPic()))
                    .placeholder(R.drawable.pic_talkbox_sel)
                    .error(R.drawable.pic_talkbox_sel)
                    .into(ivUserHead);
            tvUserName.setText(commentInfoBeanList.get(0).getEvaluater());
            tvCommentTime.setText(commentInfoBeanList.get(0).getEvaluateTime());
            tvComment.setText(commentInfoBeanList.get(0).getEvaluateTitle());

            tvCommentNumContainer.setText(appendCommentNum(commentInfoBeanList.size()));
            if (commentInfoBeanList.size() == 0) {
                tvCommentNumContainer.setText(appendCommentNum(commentInfoBeanList.size()));
            }
        }

        repertory = productDetailNetBean.getRepertory();
        tvRemainNum.setText(appendRemainNum(repertory));
        //每次进商品详情页，储存对应的id的库存量
        PreferenceUtils.putInt(this, productDetailNetBean.getProductId(), Integer
                .parseInt(repertory));
    }

    /**
     * 拼接库存数量
     * @param repertory 库存数量
     * @return 库存数量拼接字符串
     */
    private String appendRemainNum(String repertory) {
        return getString(R.string.append_remain_left) + repertory + getString(R.string
                .append_remain_right);
    }

    /**
     * 拼接评价数量字符串
     * @param size 评价的数量
     * @return 评价数量
     */
    private String appendCommentNum(int size) {
        return getString(R.string.append_comment_left) + size + getString(R.string
                .append_comment_right);
    }

    /**
     * 加载商品图片（顶部商品详情图片和底部商品参数图片）
     * @param urls 顶部viewpager的url (详情图片)
     * @param paramUrl 底部iv的url (参数图片)
     */
    private void loadPic(List<String> urls, String paramUrl) {
        //如果之上架参数图和商品图，显示出来
        if (urls != null && urls.size() > 0) {
            for (int i = 0; i < urls.size(); i++) {
                ImageView iv = new ImageView(this);
                iv.setScaleType(ImageView.ScaleType.FIT_XY);
                iv.setAdjustViewBounds(true);
                iv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup
                        .LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams
                        .WRAP_CONTENT));
                Picasso.with(this)
                        .load(StringUtils.appendPicPath(urls.get(i)))
                        .placeholder(R.drawable.pic_talkbox_sel)
                        .error(R.drawable.pic_talkbox_sel)
                        .into(iv);
                viewList.add(iv);
            }

            vpProductDetail.setAdapter(new VpProductDetailAdapter(this, viewList));
            // 添加点
            for (int i = 0; i < urls.size(); i++) {
                View point = new View(this);
                point.setBackgroundResource(R.drawable.point_dt_normal);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                        DensityUtils.dp2px(this, 6),
                        DensityUtils.dp2px(this, 6));
                if (i != 0) {
                    params.leftMargin = DensityUtils.dp2px(this, 6);
                } else {
                    point.setBackgroundResource(R.drawable.point_dt_foucs);
                }
                mPointContainer.addView(point, params);
            }
        }

        // 给viewpager设置监听
        vpProductDetail.addOnPageChangeListener(this);
        Picasso.with(this)
                .load(StringUtils.appendPicPath(paramUrl))
                .placeholder(R.drawable.pic_talkbox_sel)
                .error(R.drawable.pic_talkbox_sel)
                .into(ivProductParamPic);
    }

    @Override
    protected String activityDesc() {
        return getString(R.string.page_product_detail);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_detail);
        ButterKnife.bind(this);

        initData();
        initView();
    }

    /**
     * 初始化商品详情页面
     */
    private void initView() {
        tabTvTitle.setText(R.string.title_product_detail);
        rlBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        ivCounsel.setVisibility(View.VISIBLE);
        ivCounsel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openSaleServiceChat();
            }
        });
        tvDiscountPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);

        llTypeContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPop(ProductDetailActivity.this);
            }
        });

        btnAllComments.setOnClickListener(this);

        llAdd2cart.setOnClickListener(this);

        tvRemainNum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                netCount.setCursorVisible(false);
            }
        });

        btnBuyNow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int count = netCount.getAccount();
                if (count == 0) {
                    Toast.makeText(ProductDetailActivity.this,
                            getString(R.string.tip_shop_none), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (repertory != null) {
                    if (count > Integer.parseInt(repertory)) {
                        Toast.makeText(ProductDetailActivity.this,
                                R.string.tip_buy_exceed,
                                Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                if (!RequestUtils.checkNetwork(ProductDetailActivity.this)) {
                    return;
                }
                String productIconUrl = getIntent()
                        .getStringExtra(PRODUCT_ICON_URL);
                Intent intent = new Intent(ProductDetailActivity.this,
                        OrderConfirmActivity.class);
                intent.putExtra(SHOPPING_NUM, count);
                intent.putExtra(PRODUCT_ICON_URL, productIconUrl);
                intent.putExtra(PRODUCT_NET_BEAN, productDetailNetBean);
                intent.putExtra(TYPE_BUY, TYPE_BUY_DIRECT);

                startActivity(intent);
            }
        });
        // 详情页增加按钮点击事件
        netCount.getAddBtn().setOnClickListener(new OnMultiClickListener() {
            @Override
            public void onMultiClick(View v) {
                //网络信号差的时候，点击会出现崩溃，做非空判断，友好提示
                if (netCount != null && productDetailNetBean != null) {

                    netCount.addAccount(productDetailNetBean.getProductId());
                } else {
                    ToastUtils.toastContent(ProductDetailActivity.this, getString(R.string
                            .add_net_week));
                }
            }
        });
    }

    /**
     * 打开在线客服聊天界面
     */
    private void openSaleServiceChat() {
        try {
            List<RegisterUserNetBean> users = DatabaseHelper.getHelper(this)
                    .getDao(RegisterUserNetBean.class).queryForEq("userName", Constants.TOPIC_KSKF);
            if (users.isEmpty()) {
                return;
            }

            Intent intent = new Intent(this, ChatActivity.class);
            intent.putExtra("userId", users.get(0).getUserId());
            intent.putExtra("topicName", users.get(0).getUserName());
            intent.putExtra("nickName", users.get(0).getNickName());
            intent.putExtra("picPath", users.get(0).getUserPic());
            Gson gson = new Gson();
            intent.putExtra("data", gson.toJson(users.get(0)));
            startActivity(intent);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * init data
     */
    private void initData() {
        productInfoBean = getIntent().getParcelableExtra(PRODUCT_INFO_DATA);
        RequestUtils.findProductDetailById(productInfoBean.getProductId(), new
                RequestCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                    }

                    @Override
                    public void onResponse(ResponseBean responseBean) {
                        String resultCode = responseBean.getResultCode();
                        if (resultCode.equals(Constants.REQUEST_OK)) {
                            productDetailNetBean = responseBean.getEntity(ProductDetailNetBean
                                    .class);
                            handler.sendEmptyMessage(MSG_UPDATE_DETAIL);
                        } else {
                            llContainer.setVisibility(View.GONE);
                        }
                    }
                });
    }

    /**
     * 显示Pop窗口
     * @param context 上下文
     */
    private void showPop(final Context context) {
        ProductTypeBottomPop popwindow = new ProductTypeBottomPop(this, viewBg);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_all_comments:
                Intent intent = new Intent(this,
                        ProductAllCommentActivity.class);
                if (productDetailNetBean != null) {
                    ArrayList<CommentInfoBean> evaluates = (ArrayList<CommentInfoBean>)
                            productDetailNetBean.getEvaluates();
                    intent.putParcelableArrayListExtra(COMMENT_DATA,
                            evaluates);
                }
                startActivity(intent);
                break;
            case R.id.ll_add2cart:
                // 输入数字
                int num = netCount.getAccount();
                // 添加购物车商品数量校验
                if (num < 1) {
                    ToastUtils.toastContent(ProductDetailActivity.this, getString(R.string
                            .tip_add2cart_num_error));
                    return;
                }
                if (repertory != null) {
                    // 获取购物车的数量进行对比
                    String count = PreferenceUtils.getString(this, productDetailNetBean
                            .getProductName());
                    if (count != null) {
                        // 得到总共加入购物车数量
                        int shopCount = (Integer.parseInt(count));
                        if (shopCount != -1) {
                            shopCount = shopCount + num;
                            // 大于库存
                            if (shopCount > Integer.parseInt(repertory)) {
                                ToastUtils.toastContent(ProductDetailActivity.this,
                                        getString(R.string.tip_buy_exceed));
                                return;
                            }
                        }
                    } else {
                        // 此时购物车是空的，只比较num
                        if (num > Integer.parseInt(repertory)) {
                            ToastUtils.toastContent(ProductDetailActivity.this, getString(R.string
                                    .tip_buy_exceed));
                            return;
                        }
                    }
                }

                if (productDetailNetBean != null) {
                    final String productId = productDetailNetBean.getProductId();
                    RequestUtils.add2ShoppingCart(NetConfig.currentEmpid,
                            productId, "" + num,
                            new RequestCallback() {
                                @Override
                                public void onError(Call call, Exception e) {
                                    Toast.makeText(ProductDetailActivity.this,
                                            R.string.tip_add2cart_error,
                                            Toast.LENGTH_SHORT).show();
                                }

                                @Override
                                public void onResponse(ResponseBean responseBean) {
                                    if (responseBean.getResultCode().equals(Constants.REQUEST_OK)) {
                                        //当加入购物车成功，lsit才可以显示，不屏蔽
                                        Constants.isHideBuyList = false;
                                        /**
                                         * 商品详情添加购物车成功后，获取购物车的对应的数量，实时储存起来
                                         * 再次添加，进行比较
                                         */
                                        getShopCartCount(productId);

                                        ToastUtils.toastContent(ProductDetailActivity.this,
                                                getString(R.string.tip_add2cart_ok));
                                    }
                                }
                            });
                }
                break;
            default:
                break;
        }
    }

    /**
     * 获取购物车接口，通过产品id对比储存对应的货物数量
     * @param productId 产品id
     */
    private void getShopCartCount(final String productId) {
        RequestUtils.showCatDetail(NetConfig.currentEmpid, new
                RequestCallback() {
                    @Override
                    public void onError(Call call, Exception e) {

                    }

                    @Override
                    public void onResponse(ResponseBean responseBean) {
                        if (responseBean.getResultCode().equals(Constants
                                .REQUEST_OK)) {
                            cartDetailNetBeans = responseBean.getList(new
                                    TypeToken<List<CartDetailNetBean>>() {
                                    }.getType());
                            if (cartDetailNetBeans != null &&
                                    cartDetailNetBeans.size() > 0) {
                                for (CartDetailNetBean bean : cartDetailNetBeans) {
                                    //比较产品id
                                    if (bean.getProductId().equals(productId)) {
                                        String shopConut = bean.getShopNumber();
                                        PreferenceUtils.putString(ProductDetailActivity.this,
                                                bean.getProductName(), shopConut);
                                    }
                                }
                            }
                        }
                    }
                });
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int
            positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        int count = mPointContainer.getChildCount();
        for (int i = 0; i < count; i++) {
            View child = mPointContainer.getChildAt(i);
            child.setBackgroundResource(i == position
                    ? R.drawable.point_dt_foucs
                    : R.drawable.point_dt_normal);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
